package com.appspot.etao.service;

import java.util.ArrayList;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.jdo.Transaction;

import com.appspot.etao.jdo.PMF;
import com.appspot.etao.model.ItemCatModel;
import com.appspot.etao.model.ShopCatModel;
import com.appspot.etao.model.ShopModel;
import com.appspot.etao.model.TaobaokeItemModel;
import com.appspot.etao.model.TaobaokeShopModel;
import com.appspot.etao.model.UserModel;
import com.appspot.etao.util.ConvertUtil;
import com.taobao.top.domain.ItemCat;
import com.taobao.top.domain.Shop;
import com.taobao.top.domain.TaobaokeItem;
import com.taobao.top.domain.TaobaokeShop;
import com.taobao.top.domain.User;
import com.taobao.top.request.TaobaokeItemsGetRequest;

/**
 * 该程序由GAE自动调度，每天定时执行
 * 将Top上的数据在本地保存副本，已提高页面载入速度
 * 需要保存副本的数据有：TaobaokeItem, Shop, User
 * 在本地保存数据之前，为了避免数据重复，需要先删除本地数据库中所有已保存的数据
 */
public class CronService extends BaseService {

	private TopService topService = ServiceFactory.getTopService();
	
	private PersistenceManager pm = PMF.get().getPersistenceManager();
	
	/**
	 * 获取Top数据，并将其保存到本地
	 */
	public void getTopData(TaobaokeItemsGetRequest taobaokeRequest) {
		System.out.println("************************************************************************************");
		String cid = taobaokeRequest.getTextParams().get("cid");
		System.out.println("**CronService: Start getTopData with type: " + cid);
		
		//保存TaobaokeItem数据
		System.out.println("CronService: Start getTaobaokeItem");
		List<TaobaokeItem> allTaobaokeItemList = topService.getAllTaobaokeItemList(taobaokeRequest);
		List<TaobaokeItemModel> allTaobaokeItemModelList = ConvertUtil.convertTaobaokeItemList(allTaobaokeItemList, cid);
		pm.makePersistentAll(allTaobaokeItemModelList);
		System.out.println("CronService: End getTaobaokeItem with: " + allTaobaokeItemModelList.size() + " records!");
		
		//取得Distinct TaobaokeItem数据
		List<TaobaokeItem> distinctTaobaokeItemList = topService.getDistinctTaobaokeItemList(allTaobaokeItemList);
		
		//保存Shop数据
		System.out.println("CronService: Start getShop");
		List<Shop> shopList = topService.getShopList(distinctTaobaokeItemList);
		List<ShopModel> shopModelList = ConvertUtil.convertShopList(shopList);
		pm.makePersistentAll(shopModelList);
		System.out.println("CronService: End getShop with: " + allTaobaokeItemModelList.size() + " records!");
		
		//保存TaobaokeShop数据
		System.out.println("CronService: Start getTaobaokeShop");
		List<TaobaokeShop> taobaokeShopList = topService.getTaobaokeShopList(shopModelList);
		List<TaobaokeShopModel> taobaokeShopModelList = ConvertUtil.convertTaobaokeShopList(taobaokeShopList, cid);
		pm.makePersistentAll(taobaokeShopModelList);
		System.out.println("CronService: End getTaobaokeShop with: " + allTaobaokeItemModelList.size() + " records!");
		
		//保存User数据
		System.out.println("CronService: Start getUser");
		List<User> userList = topService.getUserList(distinctTaobaokeItemList);
		List<UserModel> userModelList = ConvertUtil.convertUserList(userList);
		pm.makePersistentAll(userModelList);
		System.out.println("CronService: End getUser  with: " + allTaobaokeItemModelList.size() + " records!\n\n");
	}
	
	/**
	 * 删除本地数据库中所有已保存的数据
	 */
	public void removeLocalData() {
		//删除本地ShopCat数据
		String shopCatQuery = "select from " + ShopCatModel.class.getName();
		List<ShopCatModel> oldShopCatModelList = (List<ShopCatModel>)pm.newQuery(shopCatQuery).execute();
		pm.deletePersistentAll(oldShopCatModelList);
		
		
		//删除TaobaokeItemModel数据
		String taobaokeItemModelQuery = "select from " + TaobaokeItemModel.class.getName();
		List<TaobaokeItemModel> taobaokeItemModelList = (List<TaobaokeItemModel>)pm.newQuery(taobaokeItemModelQuery).execute();
		pm.deletePersistentAll(taobaokeItemModelList);
		
		//删除ShopModel数据
		String shopModelQuery = "select from " + ShopModel.class.getName();
		List<ShopModel> shopModelList = (List<ShopModel>)pm.newQuery(shopModelQuery).execute();
		pm.deletePersistentAll(shopModelList);
		
		//删除TaobaokeShopModel数据
		String taobaokeShopModelQuery = "select from " + TaobaokeShopModel.class.getName();
		List<TaobaokeShopModel> taobaokeShopModelList = (List<TaobaokeShopModel>)pm.newQuery(taobaokeShopModelQuery).execute();
		pm.deletePersistentAll(taobaokeShopModelList);
		
		
		//删除UserModel数据
		String userModelQuery = "select from " + UserModel.class.getName();
		List<UserModel> userModelList = (List<UserModel>)pm.newQuery(userModelQuery).execute();
		pm.deletePersistentAll(userModelList);
	}
	
	private List<ItemCatModel> getCatchItemCatModelList() {
		Query itemCatCatchQuery = pm.newQuery(ItemCatModel.class);
//		itemCatCatchQuery.setFilter("isCatched = false");
//		itemCatCatchQuery.setRange(0, Constant.CATCH_BLOCK);
		
		List<ItemCatModel> itemCatModelList = (List<ItemCatModel>)itemCatCatchQuery.execute();
		
		if (itemCatModelList == null) itemCatModelList = new ArrayList<ItemCatModel>();
		
		return itemCatModelList;
	}
	
	private void updateCatchedItemCatModelList(List<ItemCatModel> itemCatModelList) {
		for (ItemCatModel itemCatModel : itemCatModelList) {
			itemCatModel.setCatched(true);
		}
	}
	
	/**
	 * 该程序入口
	 * 1. 获取所有Top上的商铺分类，保存到本地
	 * 2. 根据商铺分类，构造TaobaokeItemRequest对象列表
	 */
	public boolean execute(String action) {
		boolean isSuccess = true;
		
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Transaction tx = pm.currentTransaction();
//		pm.gett
		try {
			tx.begin();
			
			if (action == null || "".equals(action) || "all".equals(action) || "delete".equals(action)) {
				removeLocalData();
			}
			
			if (action == null || "".equals(action) || "all".equals(action) || "insert".equals(action)) {
				/* **商品类目获取方式错误！**
				//将Top ShopCat数据保存到本地数据库
				System.out.println("CronService: Start getShopCat");
				List<ShopCat> shopCatList = topService.getShopCatList();
				List<ShopCatModel> newShopCatModelList = ConvertUtil.convertShopCatList(shopCatList);
//				Extent shopCatModelEx = pm.getExtent(ShopCatModel.class);
				pm.makePersistentAll(newShopCatModelList);
				System.out.println("CronService: End getShopCat");
				
				//取出所有ShopCat类目中参与淘宝客推广的商品
				for (ShopCatModel shopCatModel : newShopCatModelList) {
					TaobaokeItemsGetRequest taobaokeRequest = new TaobaokeItemsGetRequest();
					taobaokeRequest.setOrderBy("credit_desc");
					taobaokeRequest.setCid(shopCatModel.getCid().toString());
					getTopData(taobaokeRequest);
				}
				*/

				//将Top ItemCat数据保存到本地数据库
				System.out.println("CronService: Start getItemCat");
				List<ItemCat> itemCatList = topService.getItemCatList();
				List<ItemCatModel> itemCatModelList = ConvertUtil.convertItemCatList(itemCatList);
				pm.makePersistentAll(itemCatModelList);
				System.out.println("CronService: End getItemCat");
	
				//取出所有ItemCat类目中参与淘宝客推广的商品
				for (ItemCatModel itemCatModel : itemCatModelList) {
					TaobaokeItemsGetRequest taobaokeRequest = new TaobaokeItemsGetRequest();
					taobaokeRequest.setOrderBy("credit_desc");
					taobaokeRequest.setCid(itemCatModel.getCid().toString());
					getTopData(taobaokeRequest);
				}
			}
			
			tx.commit();
			pm.close();
			
			isSuccess = true;
		} catch (Exception e) {
			e.printStackTrace();
			isSuccess = false;
		} finally {
			if (tx.isActive()) {
				//failure
				System.out.println("FAILURE: No local data should be effected!");
				tx.rollback();
				isSuccess = false;
			} else {
				//success
				System.out.println("SUCCESS: All local data have been updated!");
			}
		}
		return isSuccess;
	}
}
